package cn.tedu.knows.portal.service.impl;

import cn.tedu.knows.portal.exception.ServiceException;
import cn.tedu.knows.portal.mapper.ClassroomMapper;
import cn.tedu.knows.portal.mapper.UserRoleMapper;
import cn.tedu.knows.portal.model.Classroom;
import cn.tedu.knows.portal.model.User;
import cn.tedu.knows.portal.mapper.UserMapper;
import cn.tedu.knows.portal.model.UserRole;
import cn.tedu.knows.portal.service.IUserService;
import cn.tedu.knows.portal.vo.RegisterVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tedu.cn
 * @since 2021-10-27
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ClassroomMapper classroomMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public void registerStudent(RegisterVo registerVo) {
        QueryWrapper<Classroom> query = new QueryWrapper<>();
        query.eq("invite_code",registerVo.getInviteCode());
        Classroom classroom = classroomMapper.selectOne(query);

        if(classroom==null){
            throw new ServiceException("邀请码错误!");
        }

        User user = userMapper.findUserByUsername(registerVo.getPhone());

        if(user!=null){
            throw new ServiceException("手机号已经被注册!");
        }

        PasswordEncoder encoder = new BCryptPasswordEncoder();
        String pwd = "{bcrypt}"+encoder.encode(registerVo.getPassword());

        User u = new User()
                .setUsername(registerVo.getPhone())
                .setNickname(registerVo.getNickname())
                .setPassword(pwd)
                .setClassroomId(classroom.getId())
                .setCreatetime(LocalDateTime.now())
                .setEnabled(1)
                .setLocked(0)
                .setType(0);

        int num = userMapper.insert(u);
        if(num!=1){
            throw new ServiceException("数据库忙");
        }

        UserRole userRole = new UserRole()
                .setUserId(u.getId())
                .setRoleId(2);
        num = userRoleMapper.insert(userRole);
        if(num!=1){
            throw new ServiceException("数据库忙");
        }




    }



}
